package cn.vendpay.com.controller;


import cn.vendcommon.com.entity.Result;
import cn.vendcommon.com.entity.VideoItem;
import cn.vendpay.com.service.VideoService;
import cn.vendpay.com.task.ScheduledTask;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@RestController
@RequestMapping("/video")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @GetMapping("/startScan/{machineId}")
    public Result videoStart(@PathVariable("machineId") int machineId) {
//        videoService.videoStartTest(machineId, 15);
        handleVideoAndDeduction();
        return Result.success();
    }

    @GetMapping("/list/{status}")
    public Result<List<VideoItem>> getVideoListByStatus(@PathVariable("status") int status) {
        List<VideoItem> videoItems = videoService.getVideoItemsByStatus(status);
        if (CollectionUtils.isEmpty(videoItems)) {
            return Result.success();
        }
        return Result.success(videoItems);
    }


    // 业务逻辑：处理视频并执行扣费
    public void handleVideoAndDeduction() {
        // 获取视频信息
        List<VideoItem> videoItems = videoService.getVideoItemsByStatusLimitNum(0,10);
        if (CollectionUtils.isEmpty(videoItems)) {
            return;
        }
        for (VideoItem videoItem : videoItems) {
            boolean status = videoService.videoStartTestByUrl(videoItem.getUserId(),videoItem.getUrl(), videoItem.getMachineId(), 10);
            if (status){
                // 更新视频状态为处理完成
                videoItem.setProcessStatus(1);
            } else {
                // 更新视频状态为处理失败
                videoItem.setProcessStatus(0);
            }
        }
        // 统一更新视频状态为处理完成
        videoService.updateStatus(videoItems);
    }

    @GetMapping("/play/{videoId}")
    public Result<String> playVideoByVideoId(@PathVariable("videoId") int videoId) {
        String url = videoService.playVideoByVideoId(videoId);
        System.out.println("<--------------- 当前生成的预签名url = " + url + " --------------->");
        return Result.success(url);
    }

    @GetMapping("/delete/{videoId}")
    public Result deleteByVideoId(@PathVariable("videoId") int videoId) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        videoService.deleteByVideoId(videoId);
        return Result.success();
    }
}
